package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.common.ValidateCodeUtils;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        String phone = user.getPhone();
        //SMSUtils.sendMessage(phone, code.toString());
        session.setAttribute("code", code.toString());
        System.out.println("++++++++++++++++++++++++++++++++++++++++验证码是：" + code);
        return R.success("成功！");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        String loginCode = (String) map.get("code");

        String code = (String) session.getAttribute("code");

        if (code.equals(loginCode)) {
            R<User> user = userService.login(map);
            User data = user.getData();
            Long id = data.getId();
            session.setAttribute("user", id);
            session.removeAttribute("code");
            return user;
        }
        return R.error("验证失败！");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session) {
        session.removeAttribute("user");
        return R.success("成功！");
    }
}